package com.yunxiao.cloud.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

/**
 * @description: EncryptUtil
 * @author: yunxiao
 * @date: 2020/3/4 14:31
 * @version: V1.0
 **/
public class EncryptUtil {

    public static final String ALGORITHM_DESEDE = "DESede";
    public static final String ALGORITHM_DES = "DES";
    public static final String ALGORITHM_MD5 = "MD5";

    /**
     * @param algorithm
     * @param key
     * @param src
     * @return
     * @throws Throwable
     */
    public static String encrypt(String algorithm, String key, String src) throws Throwable {
        Cipher cipher = Cipher.getInstance(algorithm);
        byte[] keyByte = key.getBytes();
        SecretKey secretKey = new SecretKeySpec(keyByte, algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return new String(cipher.doFinal(src.getBytes()));
    }

    /**
     * 加密
     *
     * @param algorithm
     * @param src
     * @return
     * @throws Throwable
     */
    public static String encrypt(String algorithm, String src) throws Exception {
        if (ALGORITHM_MD5.equals(algorithm)) {
            return Md5Util.getMd5Str(src);
        } else {
            return null;
        }
    }

    /**
     * 解密
     *
     * @param algorithm
     * @param key
     * @param src
     * @return
     * @throws Throwable
     */
    public static String decrypt(String algorithm, String key, String src) throws Throwable {
        Cipher cipher = Cipher.getInstance(algorithm);
        byte[] keyByte = key.getBytes();
        SecretKey secretKey = new SecretKeySpec(keyByte, algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(src.getBytes()));
    }

    /**
     * @param algorithm
     * @return
     * @throws Throwable
     */
    private KeyPair productKeyPair(String algorithm) throws Throwable {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithm);
        keyPairGen.initialize(1024);
        return keyPairGen.generateKeyPair();
    }
}
